import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:wallpaper/api/mohu.dart';
import 'package:wallpaper/components/images/image_list.dart';
import 'package:wallpaper/model/image_base.dart';

class MoeList extends StatefulWidget {
  final String sort;
  const MoeList({super.key, required this.sort});

  @override
  State<MoeList> createState() => _MoeListState();
}

class _MoeListState extends State<MoeList> with AutomaticKeepAliveClientMixin {
  final List<ImageBase> imgs = [];
  final Set<String> results = <String>{};
  bool isLoading = false;

  Future<void> getData() async {
    if (!mounted) return;
    setState(() {
      isLoading = true;
    });
    try {
      Response res = await getMoeImgs(sort: widget.sort);
      List pics = res.data['pic'];
      for (var i = 0; i < pics.length; i++) {
        String large = pics[i].toString().replaceAll('?thumbnail=large', '');
        if (results.contains(large)) continue;
        results.add(large);
        ImageBase img = ImageBase(
          smallPath: pics[i],
          largePath: large,
          tags: '',
        );
        imgs.add(img);
      }
    } catch (e) {
      print(e);
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  @override
  void initState() {
    super.initState();
    getData();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ImageList(
      imageList: imgs,
      isLoading: isLoading,
      isPC: widget.sort == 'pc' ? true : false,
      onImageBottomLoading: () {
        if (isLoading) return;
        getData();
      },
      onImageListRefresh: () {
        setState(() {
          imgs.clear();
          results.clear();
        });
        getData();
      },
    );
  }

  @override
  bool get wantKeepAlive => true;
}
